<?php
namespace Mob\Model;
use Think\Model;
class CredFlowModel extends Model
{
 /**
  * 自动投标
  * @param unknown $loanid
  */
 public function zidongtoubiao($loanid,$seuid,$credcode)
	{
	  
	    $loadInfo = M('LoaderInfo')->find($loanid);
	    if(empty($loadInfo)){
	        return 0;
	    }
	    $realCredit=$loadInfo['money']/$loadInfo['domainnum'];
	    $InvestorInfodao= M('InvestorInfo');
	    $resu=0;
	    $condi['dd_user_assets.creditmoney']=array('egt',0);
	    $condi['dd_investor_info.is_auto']=2;
	    $condi['dd_investor_info.uid']=array('neq',$seuid);
	    $condi['dd_investor_info.term_begin']=array('elt',$loadInfo['term']);
	    $condi['dd_investor_info.term_end']=array('egt',$loadInfo['term']);
	    $condi['dd_inves_domcate.domtypeid']=$loadInfo['domaintypeid'];
	    $condi['dd_inves_domcate.rate']=array('elt',$loadInfo['rate']);//实际利率按借款人的算
	    $leavemoney=$loadInfo['money'];//还需要借的钱	    
	    
	    while(true){
    	    if($leavemoney==0){
    	         break;
    	    }
    	    $invest = $InvestorInfodao->join(' LEFT JOIN dd_user_assets on dd_investor_info.uid=dd_user_assets.uid')->join(' LEFT JOIN dd_inves_domcate on dd_investor_info.id=dd_inves_domcate.inve_id')->field('dd_investor_info.id,dd_investor_info.uid,dd_investor_info.term_begin,dd_investor_info.term_end,dd_user_assets.creditmoney')->where($condi)->order("dd_investor_info.create_time desc")->limit(1)->select();
    	    if(empty($invest)){
    	        break;
    	    }
    	    $invest=$invest[0];
    	    $realMoney=0;//实际匹配投资金额
    	    if($invest['creditmoney']>=$leavemoney){//满标
    	        $realMoney=$leavemoney;
    	    }else{//未满标
    	        $realMoney=$invest['creditmoney'];
    	    }
    	    
    	    $credFlow = M('CredFlow');
    	    $credate['loanduid']=$loadInfo['uid'];
    	    $credate['investuid']=$invest['uid'];
    	    $credate['money']=$realMoney;
    	    $tradeFee = M('TradeFee')->field('rate')->where('type=3')->select();
    	     
    	    $mortArr=array();
    	    if($loadInfo['term']-30<0){
    	        $credate['persionnum']=1;//还款期数
    	        array_push($mortArr, date("Y-m-d",strtotime($loadInfo['term']." day")).' 00:00:00');
    	        $lixi=$realMoney*($loadInfo['rate']*0.01/360)*$loadInfo['term'];
    	        $lixi=(double)(sprintf("%.2f", $lixi));
    	        $credate['interest']=$lixi;//每期利息
    	        $credate['mangrate']=($tradeFee[0]['rate'])*0.01*$realMoney;//管理费
    	    }else if($loadInfo['term']-30>=0){
    	        $credate['persionnum']=$loadInfo['term']/30;//还款期数
    	        $lixi=$realMoney*($loadInfo['rate']*0.01/12)*$credate['persionnum'];
    	        $lixi=(double)(sprintf("%.2f", $lixi));
    	        $credate['interest']=$lixi;//每期利息
    	        $credate['mangrate']=($tradeFee[0]['rate'])*0.01*$realMoney;//管理费
    	        for($i=1;$i<=$credate['persionnum'];$i++){
    	            $days=$loadInfo['term']*$i;
    	            array_push($mortArr, date("Y-m-d",strtotime($days." day")).' 00:00:00');
    	        }
    	    }
    	     
    	    $credate['rpersionum']=0;//已还期数
    	    $credate['penalty']=0;//罚息
    	    $credate['createdate']=date('y-m-d H:m:s',time());
    	    $credate['rate']=$loadInfo['rate'];//rate
    	    $credate['loanid']=$loadInfo['id'];
    	    $credate['status']=4;
    	    $credate['domtypeid']=$loadInfo['domaintypeid'];
    	    $credate['cred_code']=$credcode;
    	    /**
    	     * 到此满标
    	     */
	     if($invest['creditmoney']>=$leavemoney){
	        $credate['full_time']=date('y-m-d H:m:s',time());
	        $credate['status']=1;
	        $credFlow->add($credate);
	        /**
	         * 批量修改抵押域名状态和授信额度
	         * @var unknown
	        */
	        $loanDomainList = M('LoanDomains')->field('domainid')->where('loanid='.$loadInfo['id'])->select();
	        $crefowData['uid']=$loadInfo['uid'];
	        $credflowDomian=M('CredflowDomian');
	        foreach ($loanDomainList as $loanDomain){//修改域名从投标中变为抵押状态
	            M('UserDomains')->where('id='.$loanDomain['domainid'])->setField(array('is_mortage'=>2));
	            $crefowData['domainid']=$loanDomain['domainid'];
	            $crefowData['credit']=$realCredit;
	            $crefowData['cred_code']=$credcode;
	            $credflowDomian->add($crefowData);//添加借款域名授信表
	        }
	        //修改借款标状态为已满标
	        M('LoaderInfo')->where('id='.$loadInfo['id'])->setField(array('tovalue'=>$loadInfo['money'],'status'=>2,'full_time'=>date('y-m-d H:m:s',time())));
	        //修改借款人资金账户，加值
	        M('UserAssets')->where('uid='.$loadInfo['uid'])->setInc('avail_money',$loadInfo['money']);
	        M('UserAssets')->where('uid='.$loadInfo['uid'])->setInc('present_money',$loadInfo['money']);
	        $UserCaptdetail=M('UserCaptdetail');
	        $capdet['uid']=$loadInfo['uid'];
	        $capdet['flow_money']=$realMoney;
	        $capdet['tran_type']=1;
	        $capdet['tran_income']=4;
	        $capdet['createdate']=date('y-m-d H:m:s',time());
	        $UserCaptdetail->add($capdet);
	        //遍历处理投资人流水
	        $credlist = M("CredFlow")->field('id,investuid,money')->where("cred_code='".$credcode."'")->select();//获得所有投递此标的投资流水
	        foreach ($credlist as $cred){
	            $expiredate=date("Y-m-d",strtotime($loadInfo['term']." day")).' 00:00:00';
	            M("CredFlow")->where('id='.$cred['id'])->setField(array('status'=>1,'expiredate'=>$expiredate,'full_time'=>date('y-m-d H:m:s',time())));
	            $repaymentDa['cred_flowid']=$cred['id'];
	            $repaymentDa['loaduid']=$loadInfo['uid'];
	            $repaymentDa['investuid']=$cred['investuid'];
	            $repaymentDa['createdate']=date('y-m-d H:m:s',time());
	            $repaymentDa['is_yq']=1;
	            $repaymentDa['cred_code']=$credcode;
	            for($j=1;$j<=count($mortArr);$j++){
	                $repaymentDa['stage']=$j;
	                $repaymentDa['repaydate']=$mortArr[$j-1];
	                M('RepaymentFlow')->add($repaymentDa);
	            }
	            /**
	             * 投资人账户操作
	             *
	             */
	            if($cred['investuid']!=$invest['uid']){//从冻结的资金里扣除
	                M('UserAssets')->where('uid='.$cred['investuid'])->setDec('locked_money',$cred['money']);
	            }else{//此资金直接扣除理财宝
	                M('UserAssets')->where('uid='.$cred['investuid'])->setDec('creditmoney',$cred['money']);
	            }
	            $capdet['uid']=$cred['investuid'];
	            $capdet['flow_money']=$cred['money'];
	            $capdet['tran_type']=2;
	            $capdet['tran_income']=4;
	            $capdet['createdate']=date('y-m-d H:m:s',time());
	            $UserCaptdetail->add($capdet);
	        }
	        M('InvestorInfo')->where('id='.$invest['id'])->setInc('tovalue',$realMoney);//修改该笔投资流水实际投资额
	        $resu=1;
	     }else{//未满标
	        $credate['status']=4;
	        $credFlow->add($credate);
	        
	        M('InvestorInfo')->where('id='.$invest['id'])->setInc('tovalue',$realMoney);//修改该笔投资流水实际投资额
	        /**
	         * 投资人账户操作-减少理财宝到锁定资金账户
	         *
	        */
	        M('UserAssets')->where('uid='.session('uid'))->setDec('creditmoney',$realMoney);
	        M('UserAssets')->where('uid='.session('uid'))->setInc('locked_money',$realMoney);
	    }
	    $leavemoney=$leavemoney-$realMoney;//剩余金额
	  }
	   return $resu;
   }
   /**
    * 交易大厅进行抵押购买时调用此完成借款记录操作
    * @param unknown $uid
    * @param unknown $inveruid
    */
   public function loan($uid,$inveruid,$money,$domtypeid,$investid,$term,$rate,$domanList,$credit,$tradeFee,$cred_code){
       $credFlow = M('CredFlow');
       $credate['loanduid']=$uid;
       $credate['investuid']=$inveruid;
       $credate['money']=$money;
       $credate['domtypeid']=$domtypeid;
       $credate['investid']=$investid;
        
       $mortArr=array();
       if($term-30<0){
           $credate['persionnum']=1;//还款期数
           array_push($mortArr, date("Y-m-d",strtotime($term." day")).' 00:00:00');
           $lixi=$money*($rate*0.01/360)*$term;
           $lixi=(double)(sprintf("%.2f", $lixi));
           $credate['interest']=$lixi;//每期利息
           $credate['mangrate']=$tradeFee*0.01*$money;//管理费
       }else if($term-30>=0){
           $credate['persionnum']=$term/30;//还款期数
           $lixi=$money*($rate*0.01/12)*$credate['persionnum'];
           $lixi=(double)(sprintf("%.2f", $lixi));
           $credate['interest']=$lixi;//每期利息
           $credate['mangrate']=$tradeFee*0.01*$money;//管理费
           for($i=1;$i<=$credate['persionnum'];$i++){
               $days=30*$i;
               array_push($mortArr, date("Y-m-d",strtotime($days." day")).' 00:00:00');
           }
       }
        
       $credate['rpersionum']=0;//已还期数
       $credate['penalty']=0;//罚息
       $credate['createdate']=date('y-m-d H:m:s',time());
       $credate['rate']=$rate;//rate
       /**
        * 到此满标
       */
       $credate['full_time']=date('y-m-d H:m:s',time());
       $credate['status']=1;
       $credate['expiredate']=date("Y-m-d",strtotime($term." day")).' 00:00:00';
       $credate['cred_code']=$cred_code;
       $credflowid=$credFlow->add($credate);
       /**
        * 批量修改抵押域名状态和授信额度
        * @var unknown
       */
       $crefowData['uid']=session('uid');
       $credflowDomian=M('CredflowDomian');
       foreach ($domanList as $dom){//修改域名从投标中变为抵押状态
           $crefowData['domainid']=$dom['id'];
           $crefowData['credit']=$credit;
           $crefowData['cred_code']=$cred_code;
           $credflowDomian->add($crefowData);//添加借款域名授信表
       }
       /**
        * 插入还款期标
       */
       $repaymentDa['cred_flowid']=$credflowid;
       $repaymentDa['loaduid']=$uid;
       $repaymentDa['investuid']=$inveruid;
       $repaymentDa['createdate']=date('y-m-d H:m:s',time());
       $repaymentDa['is_yq']=1;
       $repaymentDa['cred_code']=$cred_code;
       for($j=1;$j<=count($mortArr);$j++){
           $repaymentDa['stage']=$j;
           $repaymentDa['repaydate']=$mortArr[$j-1];
           M('RepaymentFlow')->add($repaymentDa);
       }
       M('InvestorInfo')->where('id='.$investid)->setInc('tovalue',$money);
       return $credflowid;
   }
   
   function create_uuid($prefix = ""){    //可以指定前缀
       $str = md5(uniqid(mt_rand(), true));
       $uuid  = substr($str,0,8) . '-';
       $uuid .= substr($str,8,4) . '-';
       $uuid .= substr($str,12,4) . '-';
       $uuid .= substr($str,16,4) . '-';
       $uuid .= substr($str,20,12);
       $prefix=$uuid;
       return str_replace('-', '', $prefix);
   }
   
}
?>